import logging
import re
from functools import wraps
from concurrent_log_handler import ConcurrentRotatingFileHandler
import os
import sys
import datetime
import time
from app.project.doc_to_recommendation.utils.paths import DEFAULT_PATH

# 文件10M分隔，存10份
concurrent_handler = ConcurrentRotatingFileHandler(
    filename=DEFAULT_PATH["_LOG_PATH/"] / "app.log",
    encoding="utf-8",
    maxBytes=1024 * 1024 * 10,
    backupCount=10
)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(thread)d-%(process)d - %(levelname)s - %(message)s')
concurrent_handler.setFormatter(formatter)

# 日志打印时使用北京时区
def beijing(sec):
    if time.strftime('%z') == "+0800":
        return datetime.datetime.now().timetuple()
    return (datetime.datetime.now() + datetime.timedelta(hours=8)).timetuple()

formatter.converter = beijing

def log_func_call(name):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            logger = get_logger(name)
            # 记录输入参数
            logger.info('Calling func {} with args: {}, kwargs: {}'.format(func.__name__, args, kwargs))
            result = func(*args, **kwargs)
            # 记录返回值
            logger.info('{} returned: {}'.format(func.__name__, result))
            return result
        return wrapper
    return decorator

# 打印时过滤掉base64内容
class ImageDataFilter(logging.Filter):
    def filter(self, record):
        base64_pattern = re.compile(r'base64,[A-Za-z0-9+/]*={0,2}')
        for base64_msg in base64_pattern.findall(record.msg):
            record.msg = record.msg.replace(base64_msg, '***')
        return True

def get_logger(name: str):
    # 判断日志目录，不存在则新建
    if not os.path.exists(DEFAULT_PATH["_LOG_PATH/"]):
        os.mkdir(DEFAULT_PATH["_LOG_PATH/"])
    logger = logging.getLogger(name)
    logger.addHandler(concurrent_handler)
    logger.addFilter(ImageDataFilter())
    logger.setLevel(logging.INFO) if not hasattr(sys, 'DEV_ENV') else logger.setLevel(logging.DEBUG)
    return logger
